<template>
  <div>
    <div>
      <FormPanel ref="formpanel" :list="formList" :cols="2" :labelWidth="110" :isSubmitBtn="false" @formChange="changeHandle"></FormPanel>
      <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose width="700" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"></BaseDialog>
    </div>
    <div class="btnWrap">
      <el-button @click="closeDialog">取 消</el-button>
      <AjaxButton type="primary" :click="saveHandle">保 存</AjaxButton>
    </div>
  </div>
</template>

<script>
import _ from 'lodash';
import { addBusinessCustomer, customersSelect, updateBusinessCustomer } from '@/api/part/partInfoManage/contactsCustomer';
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils';

// let pinyin = require('js-pinyin');
// pinyin.setOptions({ checkPolyphone: false, charCase: 0 });
import * as validate from '@/utils/validate.js';
import pinyin, { STYLE_FIRST_LETTER } from '@/components/Pinyin/index';
import { phone, telePhone } from '@/utils/validate';

export default {
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.formData = {};
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    return {
      formList: this.createTopFilterList(),
      fetchParams: {},
      visible: false,
      handleType: '',
      dialogTitle: '',
      flagRules1: false
    };
  },
  watch: {},
  created() {
    this.init();
  },
  mounted() {
    // this.customersSelect();
  },
  methods: {
    init() {
      if (this.type === 'edit') {
        let editData = _.cloneDeep(this.rowData);
        editData.customerTypeCode = +editData.customerTypeCode;
        this.formList.forEach(x => {
          if (x.fieldName == 'salesBasePriceType') {
            if (editData[x.fieldName] != 0) {
              x.initialValue = editData[x.fieldName];
            }
          } else {
            x.initialValue = editData[x.fieldName];
          }
        });
        this.formList[this.findIndex(this.formList, 'customerCode')].disabled = true;
      }
    },
    findIndex(arr, fieldName) {
      let indexR = -1;
      arr.forEach((x, index) => {
        if (x.fieldName == fieldName) {
          indexR = index;
        }
      });
      return indexR;
    },
    createTopFilterList() {
      return [
        //   {
        //   type: 'SELECT',
        //   label: '客户类型',
        //   fieldName: 'providerType',
        //   itemList: this.createDictList('8101'),
        //   initialValue: 81011001
        // },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'customerTypeCode',
          itemList: this.createDictList(8145),
          rules: [{ required: true, message: '请选择客户类型', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '客户代码',
          maxlength: 12,
          fieldName: 'customerCode',
          rules: [
            { required: true, message: '请输入客户代码', trigger: 'blur' },
            { pattern: /^[a-zA-Z0-9_\-]{1,}$/, message: '客户代码只能为英文或者数字', trigger: 'blur' }
          ]
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          maxlength: 40,
          onInput: val => {
            const res = pinyin(val, { style: STYLE_FIRST_LETTER })
              .join('')
              .toUpperCase();
            this.$nextTick(() => {
              this.formList.find(item => item.fieldName == 'customerSpell').initialValue = res;
            });
          },
          rules: [{ required: true, message: '请输入客户名称', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '客户拼音',
          fieldName: 'customerSpell',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '客户简称',
          fieldName: 'customerShortName',
          maxlength: 30
        },
        {
          type: 'INPUT',
          label: '邮编',
          maxlength: 6,
          fieldName: 'zipCode',
          rules: [{ validator: validate.zipCode, trigger: 'blur' }]
        },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '税率',
        //   fieldName: 'tax',
        //   max: 10,
        //   min: 0,
        //   precision: 2
        // },

        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'contactorName',
          maxlength: 120,
          rules: [{ required: true, message: '请输入联系人电话', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '联系人电话',
          fieldName: 'contactorPhone',
          rules: [
            { required: true, message: '请输入联系人电话', trigger: 'blur' }
            // { validator: telePhone, message: '请输入正确的电话格式，例：021-', trigger: 'blur' }
          ]
        },
        {
          type: 'INPUT',
          label: '联系人手机',
          fieldName: 'contactorMobile',
          rules: [{ validator: phone, message: '请输入正确格式的手机号', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '传真',
          fieldName: 'fax',
          maxlength: 30
        },
        {
          type: 'SELECT',
          label: '是否有效',
          fieldName: 'isValid',
          itemList: this.createDictList('1004'),
          initialValue: 10041001
        },
        // {
        //   type: 'INPUT',
        //   label: '邮箱',
        //   fieldName: 'eMail',
        //   rules: [{ validator: validate.EmailValidate, trigger: 'blur' }]
        // },
        // {
        //   type: 'INPUT',
        //   label: '税号',
        //   fieldName: 'taxNo'
        // },
        // {
        //   type: 'INPUT',
        //   label: '开户行',
        //   fieldName: 'bank'
        // },
        // {
        //   type: 'INPUT',
        //   label: '银行账号',
        //   fieldName: 'bankAccount'
        // },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          fieldName: 'priceRate',
          initialValue: 1,
          precision: 2,
          max: 9.99
        },
        {
          type: 'SELECT',
          label: '销售基价',
          fieldName: 'salesBasePriceType',
          itemList: this.createDictList('1309')
        },
        {
          type: 'INPUT',
          label: '地址',
          maxlength: 300,
          fieldName: 'address',
          selfCols: 2
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          selfCols: 2,
          maxlength: 30
        }
        // {
        //   type: 'SELECT',
        //   label: '数据来源',
        //   fieldName: 'oemTag',
        //   itemList: this.createDictList('1045'),
        //   initialValue: 10451001,
        //   disabled: true
        // },
        // {
        //   type: 'CHECKBOX',
        //   label: '整车业务',
        //   fieldName: 'vehicleBusiness',
        //   selfCols: 0.25,
        //   options: {
        //     trueValue: 1,
        //     falseValue: 0
        //   }
        // },
        // {
        //   type: 'CHECKBOX',
        //   label: '备件业务',
        //   fieldName: 'partBusiness',
        //   selfCols: 0.25,
        //   options: {
        //     trueValue: 1,
        //     falseValue: 0
        //   }
        // },
        // {
        //   type: 'CHECKBOX',
        //   label: '精品业务',
        //   fieldName: 'boutiqueBusiness',
        //   selfCols: 0.25,
        //   options: {
        //     trueValue: 1,
        //     falseValue: 0
        //   }
        // },
        // {
        //   type: 'CHECKBOX',
        //   label: '礼品业务',
        //   fieldName: 'gitBusiness',
        //   selfCols: 0.25,
        //   options: {
        //     trueValue: 1,
        //     falseValue: 0
        //   }
        // },
        // {
        //   type: 'CHECKBOX',
        //   label: '销售公司',
        //   disabled: true,
        //   fieldName: 'salesCompany',
        //   selfCols: 0.25,
        //   options: {
        //     trueValue: 1,
        //     falseValue: 0
        //   }
        // },
      ];
    },
    async addBtn() {
      this.$refs.formpanel.SUBMIT_FORM();
    },
    changeHandle(val) {
      // this.flagRules1 = true;
      this.fetchParams = Object.assign(this.fetchParams, val);
      this.saveHandle();
    },
    async saveHandle() {
      let formData = await this.$refs.formpanel.GET_FORM_DATA();
      if (formData[0]) {
        let keys = Object.keys(formData[0]);
        notifyAction(formData[0][keys[0]][0].message, 'warning');
        return;
      } else {
        this.fetchParams = formData[1];
      }
      let res = {};
      if (this.type === 'add') {
        res = await addBusinessCustomer(this.fetchParams);
      }
      if (this.type === 'edit') {
        res = await updateBusinessCustomer(this.fetchParams);
      }
      console.log(res);
      if (res.resultCode == 200) {
        this.closeDialog('refresh');
        this.$notify({
          message: '保存成功',
          type: 'success'
        });
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    async customersSelect() {
      let res = await customersSelect();
      let json = res.data.rows.map(s => ({
        value: s.customerTypeCode,
        text: s.customerTypeName
      }));
      console.log(json);
      for (let j = 0; j < this.formList.length; j++) {
        if (this.formList[j].fieldName == 'customerTypeCode') {
          this.formList[j].itemList = json;
          return;
        }
      }
    }
  }
};
</script>

<style scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
